package com.mingqijia.gassafety.console.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.db.entity.BusinessNotice;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.constant.OperateRecordEnum;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.log.LogRecord;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.BusinessNoticeRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentPeriodRequest;
import com.mingqijia.gassafety.webserver.response.BusinessNoticeParamRes;
import com.mingqijia.gassafety.webserver.response.BusinessNoticeResponse;
import com.mingqijia.gassafety.webserver.service.BusinessNoticeService;
import com.mingqijia.gassafety.webserver.service.BusinessNoticeTemplateService;
import com.mingqijia.gassafety.webserver.service.strategy.CallTaskServiceStrategyImpl;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import javax.validation.Valid;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 业务通知
 *
 * @author guoliang.lao
 * @since 2022-04-28
 */

@Slf4j
@Api(tags = "业务通知")
@RestController(value = "BusinessNoticeController")
@RequestMapping("/business/v1/businessNotice")
public class BusinessNoticeController {

    @Autowired
    BusinessNoticeService businessNoticeService;
    
    @Autowired
    BusinessNoticeTemplateService businessNoticeTemplateService;
    
    @Autowired
    CallTaskServiceStrategyImpl callTaskServiceStrategy;


    @ApiOperation("业务通知参数名称下拉列表")
    @RequestMapping(value = "paramList", method = RequestMethod.GET)
    public CommonResponse<List<BusinessNoticeParamRes>> paramList(){
        List<BusinessNoticeParamRes> resultList = businessNoticeTemplateService.getTemplateParamList();
        return CommonResponse.success(resultList);
    }

    @ApiOperation("业务通知列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public CommonResponse<PageUtil<BusinessNoticeResponse>> list(@RequestParam @ApiParam(value = "简称") String paramName,
                                                                 @RequestParam @ApiParam(value = "参数") String paramCode,
                                                                 @RequestParam @ApiParam(value = "页码") Integer page,
                                                                 @RequestParam @ApiParam(value = "每页数量") Integer pageSize){
        return CommonResponse.success(businessNoticeService.getList(paramName,paramCode,page,pageSize));
    }


    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_27)
    @ApiOperation("新增")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public CommonResponse<Object> create(@RequestBody @Valid BusinessNoticeRequest req){
        businessNoticeService.create(req);
        return CommonResponse.success(null);
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_28)
    @ApiOperation("编辑")
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public CommonResponse<Object> edit(@RequestBody @Valid BusinessNoticeRequest req){
        if (req.getId() == null || req.getId() == 0) {
            return CommonResponse.failure("id不能为空！");
        }
        //判断 若参数为 cockpit_title, 限制参数值
        if ("cockpit_title".equals(req.getParamCode())){
           if (!req.getParamValue().matches("^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,14}$")){
               throw new BizException("驾驶舱Title请填写1-14位汉字、字母、数字.");
           }
        }
        String spId = ApplicationUtils.getWorkingSpId();
        LambdaQueryWrapper<BusinessNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessNotice::getSpId,spId).eq(BusinessNotice::getIsDeleted,0)
                .eq(BusinessNotice::getId,req.getId());
        BusinessNotice businessNotice = businessNoticeService.getOne(queryWrapper);
        Map<String, String> hashMap = businessNoticeService.EquipmentManufacturerMap();
        // 由于数据存储方式不同，需要特殊处理
        if (businessNotice.getParamCode().equals("device_offline_automation")) {
            if (businessNotice.getSetRange().equals("1")){
                businessNotice.setSetRange("所有设备");
            }else if (businessNotice.getSetRange().equals("2")){
                businessNotice.setSetRange("设备类型");
            }else if (businessNotice.getSetRange().equals("3")){
                businessNotice.setSetRange("设备型号");
            }
            if (!StringUtils.isEmpty(businessNotice.getEquipmentType())){
                if (businessNotice.getEquipmentType().contains(";")){
                    List<String> split = Arrays.asList(businessNotice.getEquipmentType().split(";"));
                    StringBuilder equipmentType = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentType.append(";");
                        }
                        equipmentType.append(EquipmentType.parse(split.get(i)).getName());
                    }
                    businessNotice.setEquipmentType(equipmentType.toString());
                }else {
                    businessNotice.setEquipmentType(EquipmentType.parse(businessNotice.getEquipmentType()).getName());
                }
            }
            if (!StringUtils.isEmpty(businessNotice.getEquipmentManufacturer()) ){
                if (businessNotice.getEquipmentManufacturer().contains(";")){
                    List<String> split = Arrays.asList(businessNotice.getEquipmentManufacturer().split(";"));
                    StringBuilder equipmentManufacturer = new StringBuilder();
                    for (int i = 0; i < split.size(); i++) {
                        if (i != 0) {
                            equipmentManufacturer.append(";");
                        }
                        equipmentManufacturer.append(hashMap.get(split.get(i)));
                    }
                    businessNotice.setEquipmentManufacturer(equipmentManufacturer.toString());
                }else {
                    businessNotice.setEquipmentManufacturer(hashMap.get(businessNotice.getEquipmentManufacturer()));
                }
            }
        }
        log.info("businessNotice:{}",businessNotice);
        if (businessNotice == null) {
            return CommonResponse.failure("编辑的数据不存在！");
        }
        
        businessNoticeService.edit(req, spId,businessNotice);
        return CommonResponse.success(null);
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_28)
    @ApiOperation("详情")
    @RequestMapping(value = "view", method = RequestMethod.GET)
    public CommonResponse<BusinessNoticeResponse> view(@RequestParam Map<String, String> req){
        if ( ObjectUtils.isEmpty(req.get("id"))  && 
                StringUtils.isEmpty(req.get("paramCode")) ){
            return CommonResponse.failure("id、param_code不能同时为空！");
        }
        BusinessNoticeResponse response = businessNoticeService.detail(req);
        if( null == response ){
            return CommonResponse.failure("未找到相应记录！");
        }
        return CommonResponse.success(response);
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_29)
    @ApiOperation("删除")
    @RequestMapping(value = "del", method = RequestMethod.GET)
    public CommonResponse<Object> del(@RequestParam @ApiParam(value = "id") Integer id){
        String spId = ApplicationUtils.getWorkingSpId();
        LambdaQueryWrapper<BusinessNotice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessNotice::getSpId,spId).eq(BusinessNotice::getIsDeleted,0)
                .eq(BusinessNotice::getId,id);
        BusinessNotice businessNotice = businessNoticeService.getOne(queryWrapper);
        if (businessNotice == null) {
            return CommonResponse.failure("删除的数据不存在！");
        }

        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setDetail("【"+businessNotice.getParamName()+"】");
        vo.setCommonInfo(businessNotice.getParamName());
        LogRecordAspect.threadLocal.set(vo);

        businessNoticeService.del(id);
        return CommonResponse.success(null);
    }

    @RequestMapping(value = "test", method = RequestMethod.GET)
    public void test(@RequestParam @ApiParam(value = "type") Integer type){
        Set<String> phones = new TreeSet<>();
        phones.add("18321969821");
        callTaskServiceStrategy.sendCallTask(
                "ae93fdddd22a4fe69cf90f06af71923a",
                phones,
                "865714060067220-1-1-1-1",
                type,
                null);
    }
}

